﻿using System;
using System.Collections.Generic;
using System.Linq;
using Tauren.Business.DLL.AccountInfo;
using Tauren.Business.DLL.Resouces;
using Tauren.Business.Entity.Config;
using Tauren.Business.Entity.Const;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Input;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Common;
using Tauren.Business.Infrastructure.Globals;
using Tauren.Business.Service.Base;
using Global = Tauren.Business.Entity.Global;
using Input = Tauren.Business.Entity.Input;
using Model = Tauren.Business.Entity.Model;
using OutPut = Tauren.Business.Entity.Output;

namespace Tauren.Business.Service.AccountInfo
{
    /// <summary>
    /// 账户信息
    /// </summary>
    public class AccountInfoService : BaseService, IAccountInfoService
    {
        public AccountInfoService(IAccountInfoBusiness business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness menuResources) : base(business, connectionBLL, menuResources)
        {
            this.ResourcesInfo = this.GetResources(GlobalConst.RESOURCES_FLAG_MODULE_ACCOUNT_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_ACCOUNT_KEY.ToLower());
            this.business = business;
        }

        private IAccountInfoBusiness business { get; set; }

        /// <summary>
        /// 删除账户信息
        /// </summary>
        /// </summary>
        /// <param name="model">人员基本信息实体</param>
        /// <returns></returns>
        public IResponseMessage Delete(object id) => business.Delete(id).Succeed();

        /// <summary>
        /// 根据账号获取账户信息
        /// </summary>
        /// </summary>
        /// <param name="model">人员基本信息实体</param>
        /// <returns></returns>
        public IResponseMessage GetByAccount(string Account)
        {
            Model.AccoutInfo accoutInfo = business.GetByAccount(Account);
            OutPut.AccoutInfo_OutPut _OutPut = new OutPut.AccoutInfo_OutPut();
            ToViewModel<Model.AccoutInfo, OutPut.AccoutInfo_OutPut>(accoutInfo, out _OutPut);
            if (_OutPut != null)
            {
                _OutPut.Dic_Creator = ToSingeUserInfoName(_OutPut.Creator, Global.Language);
                _OutPut.Dic_Modifier = ToSingeUserInfoName(_OutPut.Modifier, Global.Language);
            }
            return _OutPut.Succeed();
        }


        /// <summary>
        /// 获取单个数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IResponseMessage FirstOrDefault(object id)
        {
            Model.AccoutInfo accoutInfo = business.Get<Model.AccoutInfo>(id);
            OutPut.AccoutInfo_OutPut _OutPut = new OutPut.AccoutInfo_OutPut();
            ToViewModel<Model.AccoutInfo, OutPut.AccoutInfo_OutPut>(accoutInfo, out _OutPut);
            if (_OutPut != null)
            {
                _OutPut.Dic_Creator = ToSingeUserInfoName(_OutPut.Creator, Global.Language);
                _OutPut.Dic_Modifier = ToSingeUserInfoName(_OutPut.Modifier, Global.Language);
            }
            return _OutPut.Succeed();
        }
        /// <summary>
        /// 获取所有数据
        /// </summary> 
        /// <returns></returns>
        public IResponseMessage All()
        {
            List<Model.AccoutInfo> accoutInfos = business.All<Model.AccoutInfo>();
            List<OutPut.AccoutInfo_OutPut> _OutPuts = new List<OutPut.AccoutInfo_OutPut>();
            ToViewModel<List<Model.AccoutInfo>, List<OutPut.AccoutInfo_OutPut>>(accoutInfos, out _OutPuts);
            if (_OutPuts.Any())
            {
                _OutPuts.ForEach(o =>
                {
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Modifier = EmpDictionary.ContainsKey(o.Modifier) ? EmpDictionary[o.Modifier] : "";
                });
            }
            return _OutPuts.Succeed();
        }

        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IResponseMessage Add(Input.AccoutInfo_Input input)
        {
            Model.AccoutInfo model = null;
            ToModel<Model.AccoutInfo, Input.AccoutInfo_Input>(input, out model);
            if (model == null)
                return ErrorType.BUSINESS_ACCOUNT_NOTFOUND_INPUT_DATA_ERROR.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNT_NOTFOUND_INPUT_DATA_ERROR));
            model.Creatdate = DateTime.Now;
            model.Modifier = Global.EmpId;
            model.Creator = Global.EmpId;
            model.Modifdate = DateTime.Now;
            var dbModel = business.GetByAccount(model.Account);
            if (dbModel == null)
            {
                return business.Add(model).Succeed();
            }
            else return ErrorType.BUSINESS_ACCOUNTINFO_REPEAT_ACCOUNT.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNTINFO_REPEAT_ACCOUNT));
        }
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IResponseMessage Editor(Input.AccoutInfo_Input input)
        {
            Model.AccoutInfo model = null;
            ToModel<Model.AccoutInfo, Input.AccoutInfo_Input>(input, out model);
            if (model == null)
                return ErrorType.BUSINESS_ACCOUNT_NOTFOUND_INPUT_DATA_ERROR.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNT_NOTFOUND_INPUT_DATA_ERROR));
            model.Modifier = Global.EmpId;
            model.Modifdate = DateTime.Now;
            var dbModel = business.GetByAccount(model.Account);
            if (dbModel != null)
            {
                model.Creatdate = dbModel.Creatdate;
                model.Creator = dbModel.Creator;
                return business.Update(model).Succeed();
            }
            else return ErrorType.BUSINESS_ACCOUNT_DB_NOT_FOUND.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNT_DB_NOT_FOUND));
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        public IResponseMessage Pages(Global.QueryModel queryModel)
        {
            TableListModel<AccountListModel> tableListModel = new TableListModel<AccountListModel>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "rowNo", Name = this.Resources("rowno"), Width = 90, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "accountId", Name = this.Resources("accountid"), Width = 200, Hide = true });
            Headers.Add(new TableListHeaderModele() { Key = "name", Name = this.Resources("neme"), Type = "primary_name", Filter = true, Width = 240, Fixed = true, SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "account", Name = this.Resources("account"), Width = 200, Type = "primary_key", IsOperation = true, Filter = true, Fixed = true, SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "empId", Name = this.Resources("empid"), Width = 120, Hide = true });
            Headers.Add(new TableListHeaderModele() { Key = "empName", Name = this.Resources("empname"), Width = 200, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "organizationId", Name = this.Resources("organizationid"), Width = 120, Hide = true });
            Headers.Add(new TableListHeaderModele() { Key = "organizationName", Name = this.Resources("organizationname"), Width = 120 });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Enable", Name = CommonText("thstate"), IsTag = true, Width = 100, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creator", Name = CommonText("diccreator"), Width = 120, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creatdate", Name = CommonText("diccreatdate"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "action", Name = "操作", Width = 160, Align = "center" });
            List<AccountListModel> employeeListModels = new List<AccountListModel>();
            long Total = 0;
            List<Entity.Model.PageAccountModel> pageEployees = business.Pages(queryModel, out Total);
            if (pageEployees.Any())
            {
                ToViewModels(pageEployees, out employeeListModels);
                employeeListModels.ForEach(o =>
                {
                    o.OrganizationName = OrgDictionary.ContainsKey(o.OrgId) ? OrgDictionary[o.OrgId] : "";
                    o.EmpName = EmpDictionary.ContainsKey(o.EmpId) ? EmpDictionary[o.EmpId] : "";
                    o.Row_Style = o.Enable ? "" : "danger";
                    o.Operations = new List<SystemButton>();
                    o.Dic_Enable = CommonText(o.Enable ? GlobalConst.RESOURCES_CONTENT_ENABLE_KEY : GlobalConst.RESOURCES_CONTENT_DISABLE_KEY);
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Creatdate = o.Creatdate is null ? "" : o.Creatdate.Value.ToString(GlobalConst.DATE_FORMAT_SECONDS);

                    if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
                    {
                        BuliderButtons(o.Operations, o.Account, o.AccountId, ButtomType.restpassword);
                        BuliderButtons(o.Operations, o.Account, o.AccountId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        BuliderButtons(o.Operations, o.Account, o.AccountId, ButtomType.delete);
                    }
                    else
                    {
                        Buttons.Where(o => o.Location == ButtomLocation.center.ToString() && o.Value != ButtomType.add.ToString()).ToList().ForEach(p =>
                        {
                            o.Operations.Add(new SystemButton() { Label = p.Label, Location = ButtomLocation.center.ToString(), Icon = p.Icon, KeyFieldValue = o.Account, PrimaryKeyValue = o.AccountId, Shape = p.Shape, Size = p.Size, Type = "text", Value = p.Value });
                        });
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.restpassword.ToString()))
                            BuliderButtons(o.Operations, o.Account, o.AccountId, ButtomType.restpassword);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && (o.Value == ButtomType.enable.ToString() || o.Value == ButtomType.disable.ToString())))
                            BuliderButtons(o.Operations, o.Account, o.AccountId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.delete.ToString()))
                            BuliderButtons(o.Operations, o.Account, o.AccountId, ButtomType.delete);
                    }
                });
            }
            tableListModel.Body = employeeListModels;
            tableListModel.Total = Total;
            tableListModel.Header = Headers;
            if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
            {
                BuliderButtons(tableListModel.Operations, "", 0, ButtomType.batchregister, BtnShapeType.plain.ToString());
            }
            else
            {
                if (Buttons.Any(o => o.Value == ButtomType.batchregister.ToString())) BuliderButtons(tableListModel.Operations, "", 0, ButtomType.batchregister, BtnShapeType.plain.ToString());
            }
            return tableListModel.Succeed();
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public IResponseMessage Enable(int id)
        {
            Model.AccoutInfo accoutInfo = business.Get<Model.AccoutInfo>(id);
            if (accoutInfo == null) return ErrorType.BUSINESS_ACCOUNT_DB_NOT_FOUND.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNT_DB_NOT_FOUND));
            accoutInfo.Enable = !accoutInfo.Enable;
            accoutInfo.Modifier = Global.EmpId;
            accoutInfo.Modifdate = DateTime.Now;
            bool b = business.Update<Model.AccoutInfo>(accoutInfo);
            if (b) return "".OnSucceed(this.CommonText(accoutInfo.Enable ? GlobalErrorType.GLOBAL_ENABLE_SUCCESSINFO : GlobalErrorType.GLOBAL_DISABLE_SUCCESSINFO));
            else return accoutInfo.Enable ? GlobalErrorType.GLOBAL_ENABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_ENABLE_FAILURE)) : GlobalErrorType.GLOBAL_DISABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DISABLE_FAILURE));

        }

        /// <summary>
        /// 根据组织获取员工基本信息
        /// </summary>
        /// <param name="OrgId"></param>
        /// <returns></returns>
        public IResponseMessage GetByOrgs(string OrgId)
        {
            List<Model.AccoutInfo> accoutInfos = business.GetByOrgs(OrgId);
            List<OutPut.AccoutInfo_OutPut> _OutPuts = new List<OutPut.AccoutInfo_OutPut>();
            ToViewModel<List<Model.AccoutInfo>, List<OutPut.AccoutInfo_OutPut>>(accoutInfos, out _OutPuts);
            if (_OutPuts.Any())
            {
                _OutPuts.ForEach(o =>
                {
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Modifier = EmpDictionary.ContainsKey(o.Modifier) ? EmpDictionary[o.Modifier] : "";
                });
            }
            return _OutPuts.Succeed();
        }

        /// <summary>
        /// 注册账号
        /// </summary>
        /// <param name="Accounts"></param>
        /// <returns></returns>
        public IResponseMessage Register(List<PersonInfo_InPut> Accounts)
        {
            string key = "123456Aa".AESEncrypt();
            List<Model.AccoutInfo> accoutInfos = new List<Model.AccoutInfo>();
            Accounts.ForEach(p =>
            {
                accoutInfos.Add(new Model.AccoutInfo()
                {
                    Account = p.EmpCode,
                    EmpId = p.EmpId,
                    Name = p.CNName,
                    Enable = true,
                    Password = key,
                    Creatdate = DateTime.Now,
                    Creator = Global.EmpId,
                    Modifdate = DateTime.Now,
                    Modifier = Global.EmpId,
                    Sequence = Global.EmpId,
                    Language = "zh-cn"
                });
            });
            return business.Add<List<Model.AccoutInfo>>(accoutInfos).Succeed();
        }

        public IResponseMessage RestPassword(int AccountId)
        {
            string key = "123456Aa".AESEncrypt();
            var dbModel = business.Get<AccoutInfo>(AccountId);
            if (dbModel != null)
            {
                dbModel.Modifier = Global.EmpId;
                dbModel.Modifdate = DateTime.Now;
                return business.Update(dbModel) ? "".OnSucceed(this.Resources(ErrorType.BUSINESS_ACCOUNT_RESET_PASSWORD_SUCCESS)) : ErrorType.BUSINESS_ACCOUNT_RESET_PASSWORD_SAVE_FAILURE.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNT_RESET_PASSWORD_SAVE_FAILURE));
            }
            else return ErrorType.BUSINESS_ACCOUNT_DB_NOT_FOUND.Failure(this.Resources(ErrorType.BUSINESS_ACCOUNT_DB_NOT_FOUND));
        }
    }
}
